package com.hiyee.files.controller;

import com.hiyee.api.controller.files.FileUploadControllerApi;
import com.hiyee.api.controller.user.ArticleControllerApi;
import com.hiyee.exception.GraceException;
import com.hiyee.files.config.FileResource;
import com.hiyee.files.service.UploadService;
import com.hiyee.grace.result.ResponseJsonResult;
import com.hiyee.grace.result.ResponseStatusEnum;
import com.hiyee.pojo.bo.AdminUserLoginBO;
import com.hiyee.pojo.bo.UpdateAdminUserBO;
import com.hiyee.utils.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FileUploadController implements FileUploadControllerApi {

    final static Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    UploadService uploadService;

    @Autowired
    FileResource fileResource;

    //@Autowired
    //GridFSBucket gridFSBucket;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private ArticleControllerApi articleControllerApi;

    @Override
    public ResponseJsonResult uploadFace(String userId, MultipartFile file) throws Exception {

        // 上传文件为空
        if(file == null) {
            return ResponseJsonResult.error(ResponseStatusEnum.UPLOAD_FILE_NOT_FOUND);
        }

        // 获取文件上传名称
        String fileName = file.getOriginalFilename();
        // 文件名不能为空
        if(StringUtils.isBlank(fileName)) {
            return ResponseJsonResult.error(ResponseStatusEnum.UPLOAD_FILE_NAME_ERROR);
        }

        // 获取文件后缀
        String fileNameArr[] = fileName.split("\\.");
        String suffix = fileNameArr[fileNameArr.length - 1];
        // 判断文件后缀
        if(!suffix.equalsIgnoreCase("png")
                && !suffix.equalsIgnoreCase("jpg")
                && !suffix.equalsIgnoreCase("jpeg")) {
            return ResponseJsonResult.error(ResponseStatusEnum.UPLOAD_FILE_SUFFIX_ERROR);
        }

        // 执行上传
        String path = uploadService.ossUpload(file, userId, suffix);
        if(StringUtils.isBlank(path)) {
            return ResponseJsonResult.error(ResponseStatusEnum.UPLOAD_FILE_FAIL);
        }

        return ResponseJsonResult.success(path);
    }

    @Override
    public ResponseJsonResult getFile() {
        return ResponseJsonResult.success(1);
    }

    public ResponseJsonResult uploadGridFS(UpdateAdminUserBO updateAdminUserBO) throws Exception {
        String base64 = updateAdminUserBO.getImg64();
        // 将base64字符串转换为byte数组
        byte[] base64Arr = new BASE64Decoder().decodeBuffer(base64.trim());
        // 转化输入流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64Arr);

        //ObjectId fileId = gridFSBucket.uploadFromStream(updateAdminUserBO.getUsername() + ".png", byteArrayInputStream);

        //String stringId = fileId.toString();
        return ResponseJsonResult.success(1);
    }

    @Override
    public void readInGridFS(String faceId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if(StringUtils.isBlank(faceId)) {
            GraceException.display(ResponseStatusEnum.FILE_FACE_ID_NOT_FOUD);
        }
        // 从 gridFS 读取
        // File file = readFileInGridFS(faceId);

        // 人脸图片输出到浏览器
        FileUtils.downloadFileByStream(response, null);
    }

//    private File readFileInGridFS(String faceId) throws Exception{
//        GridFSFindIterable gridFSFindIterable = gridFSBucket.find(Filters.eq("_id", new ObjectId(faceId)));
//        GridFSFile gridFSFile = gridFSFindIterable.first();
//        if(gridFSFile == null) {
//            GraceException.display(ResponseStatusEnum.FILE_FACE_ID_NOT_FOUD);
//        }
//        String fileName = gridFSFile.getFilename();
//        // 获取文件流，保存到本地
//        File file = new File("F:/download/" + fileName);
//        // 创建文件输出流
//        OutputStream outputStream = new FileOutputStream(file);
//        // 下载到服务器
//        gridFSBucket.downloadToStream(faceId, outputStream);
//        return file;
//    }

    @Override
    public ResponseJsonResult uploadFiles(String userId, MultipartFile[] files) throws Exception {
        // list 存放多个图片地址，返回前端
        List<String> imageUrlList = new ArrayList<>();
        if(files != null && files.length > 0) {
            for (MultipartFile file : files) {
                // 上传文件为空
                if(file == null) {
                    continue;
                }

                // 获取文件上传名称
                String fileName = file.getOriginalFilename();
                // 文件名不能为空
                if(StringUtils.isBlank(fileName)) {
                    continue;
                }

                // 获取文件后缀
                String fileNameArr[] = fileName.split("\\.");
                String suffix = fileNameArr[fileNameArr.length - 1];
                // 判断文件后缀
                if(!suffix.equalsIgnoreCase("png")
                        && !suffix.equalsIgnoreCase("jpg")
                        && !suffix.equalsIgnoreCase("jpeg")) {
                    continue;
                }

                // 执行上传
                String path = uploadService.ossUpload(file, userId, suffix);
                if(StringUtils.isBlank(path)) {
                    imageUrlList.add(path);
                }
            }
        }
        return ResponseJsonResult.success(imageUrlList);
    }

    @Override
    public ResponseJsonResult eurekaFiles() {
//        System.out.println("微服务端口：" + this.serverPort);
//        // 使用 eureka 调用 article 服务
//        String serviceId = "SERVICE-ARTICLE";
//        ServiceInstance serviceInstance = discoveryClient.getInstances(serviceId).get(0);
//        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "article/hello";
//        String url = "http://" + serviceId + "/article/hello";

        AdminUserLoginBO adminUserLoginBO = new AdminUserLoginBO();
        // 使用 feign 调用
        ResponseJsonResult bodyResult = articleControllerApi.hello();

        // ResponseEntity<ResponseJsonResult> responseEntity = restTemplate.getForEntity(url, ResponseJsonResult.class);
        // ResponseJsonResult bodyResult = responseEntity.getBody();
        System.out.println("[管理员服务] 返回值：" + bodyResult.getData().toString());
        return ResponseJsonResult.success();
    }
}
